<template>
    <el-dialog class="serviceedit" title="更换服务" top="50px" ref="serviceEdit" :visible.sync="showEditForm" :before-close="handleClose" width="42%">
        <el-form v-loading="submitLoading" element-loading-text="正在提交数据，请稍等" :model="form" ref="ruleForm" class="customForm" :rules="rules">
            <el-form-item label="视频流URL" :label-width="formLabelWidth" class="formText" prop="streamURL">
                <p class="inlineText">{{getStreamURL}}</p>
            </el-form-item>
            <el-form-item label="频道名称" :label-width="formLabelWidth" class="formItem" prop="channelName">
                <el-input v-model="form.channelName" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="绑定功能" prop="type" :label-width="formLabelWidth" class="formItem">
                <el-cascader :options="options" v-model="form.type"></el-cascader>
            </el-form-item>    
            <el-form-item label="mask绘制" :label-width="formLabelWidth" class="formItem" prop="mask">
                <div class="switchItem"><el-switch v-model="form.mask" @change="handleMaskToggle"></el-switch></div>
                <el-button v-if="form.mask" type="primary" title="更换mask图片" icon="icon-third-jietu" circle size="mini" @click="reFetchImg"></el-button>
            </el-form-item>  
            <common-loading :loading="imgLoading" :loadingText="imgloadingText" size="small">
                <i slot="loadingIcon" class="el-icon-loading"></i>
            </common-loading>
            <draw-mask v-show="showCanvas" class="formItem" canvasId="canvasEdit" :url="canvasImg" 
            :width="canvasWidth" :height="canvasHeight" :show.sync="showCanvas" loadingTextColor="#fff"
            @CanvasComplete="CanvasComplete" @renderError="renderError" loadingSize="small"></draw-mask>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleReset" :disabled="submitLoading">重 置</el-button>
            <el-button type="primary" @click="handleSubmit" :disabled="submitLoading">提 交</el-button>
        </div>
    </el-dialog>
</template>
<script>
    import DrawMask from "./DrawMask.vue"
    import util from '../util/util'
    import CommonLoading from "../components/CommonLoading.vue"
    export default {
        components:{
            DrawMask,
            CommonLoading
        },
        props:{
            showEditForm:{
                type:Boolean,
                default:false
            },
            serviceObj:{
                type:Object,
                required:true
            }
        },
        data(){
            return{
                submitLoading:false,
                imgLoading:false,
                imgloadingText:'努力加载中',
                showCanvas:false,
                canvasWidth:0,
                canvasHeight:0,
                canvasImg:"",
                form: {
                    streamURL:'',
                    channelName: '',
                    type: [],
                    mask: false,
                    maskInfo: {}
                },
                formLabelWidth: '100px',
                options:[],
                rules: {
                    channelName:[
                        { required: true, message: '频道名称不能为空', trigger: 'blur'}
                    ],
                    type:[
                        { required: true, message: '绑定功能不能为空', trigger: 'blur'}
                    ]
                }
            }
        },
        computed:{
            getStreamURL:function(){
                return this.serviceObj.streamURL;
            }
        },
        watch:{
            showEditForm:{
                handler(){
                    this.form.channelName =  this.serviceObj.channelName;
                    // this.form.type = [];
                    // this.form.type.push(this.serviceObj.type);
                    // this.form.type.push(this.serviceObj.childType);
                    // console.log(this.form.type)
                },
                deep: true
                
            }
        },
        created(){
            this.getCategory();
        },
        methods:{
            getCategory(){
                this.$api.service.functionList().then(response=>{
                    if(response.data.code == "6000"){
                        this.processData(response.data.data);
                    }
                }).catch(error=>{
                });   
            },
            processData(data){
                let tmpData = [];
                for(let i in data){
                    let cateobj = {};
                    cateobj["value"] = data[i]["id"];
                    cateobj["label"] = data[i]["name"];
                    cateobj["children"] = data[i]["category"];
                    tmpData.push(cateobj);
                }
                this.options = tmpData;
            },
            handleMaskToggle(){
                if(this.form.mask){
                    //请求图片路径
                    this.fetchImg();
                }else{
                    this.resetFlag();
                }  
            },
            CanvasComplete(val){
                this.form.maskInfo["width"] = this.canvasWidth;
                this.form.maskInfo["height"] = this.canvasHeight;
                this.form.maskInfo["coordinate"] = val;
            },
            hasDrawInfo(){
                let arr = Object.keys(this.form.maskInfo);
                if(!(arr.length != 0 && this.form.maskInfo["coordinate"].length != 0)){
                    return false;
                }
                return true;
            },
            handleClose(){
                this.$emit('update:showEditForm', false);
                this.$store.dispatch("updateServiceData", false);
                this.handleReset();
            },
            handleSubmit(){
                if(this.form.mask){
                    if(!this.hasDrawInfo()){
                        this.$message({
                            message: "请在图像上绘制mask并保存；如不需要绘制，请关闭mask绘制开关",
                            type: 'info'
                        });
                        return false;
                    }
                }
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        let params = { 
                            guid: this.serviceObj.serviceId,
                            name: this.form.channelName,
                            function_id: this.form.type[0],
                            mask: this.form.mask?JSON.stringify(this.form.maskInfo):'',
                            category: this.form.type[1]
                        };
                        this.submitLoading = true;
                        this.$api.service.serviceUpdate(params).then(response=>{
                            this.submitLoading = false;
                            if(response.data.code=="6000"){
                                this.$message({
                                    type: 'success',
                                    message: '修改成功!'
                                 });
                                this.$store.dispatch("updateServiceData", true);
                            }else{
                                this.$message({
                                    type: 'error',
                                    message: util.getErrorInfo(response.data.code)
                                });
                            }
                        }).then(()=>{
                            this.$emit('update:showEditForm', false);
                            this.handleReset(); 
                        }).catch(error=>{
                            this.submitLoading = false;
                            this.$emit('update:showEditForm', false);
                            this.handleReset(); 
                        });
                    } else {
                        // console.log('error submit!!');
                        return false;
                    }
                });
                
            },
            handleReset(){
                this.resetFlag();
                this.$refs.ruleForm.resetFields();
                this.form.maskInfo = {};
            },
            reFetchImg(){
                this.resetFlag();
                this.fetchImg(true);
            },
            fetchImg(update=false){
                //请求图片
                this.imgLoading = true;
                let params = { 
                    source_url: this.getStreamURL,
                    update:update   //是否更新截图
                };
                this.$api.service.maskImageQuery(params).then(response => {
                    if(response.data.code == "6000"){
                        if(response.data.data.mask_path){
                            this.setCanvasWidthAndHeight();
                            this.canvasImg = "/api"+response.data.data.mask_path;
                            this.showCanvas = true;
                        }
                        this.imgLoading = false;
                        
                    }else{
                        this.$message({
                            message: util.getErrorInfo(response.data.code),
                            type: 'error'
                        });
                        this.imgError("图片获取失败");
                    }
					
				}).catch(error => {
                    this.imgError("图片获取失败");
				});
            },
            setCanvasWidthAndHeight(){
                let w = document.documentElement.clientWidth || document.body.clientWidth;
                let dialogWidth = parseInt(w * (parseInt(this.$refs.serviceEdit.style.width)/100));
                this.canvasWidth = dialogWidth - parseInt(dialogWidth*0.1) - 120;
                this.canvasHeight = parseInt(this.canvasWidth*(2/3));
            },
            resetFlag(){
                this.imgLoading = false;
                this.showCanvas = false;
                this.imgloadingText = "努力加载中";
            },
            renderError(val){
                if(val){
                    this.imgError("图片渲染失败，请稍后重试!");
                    // this.$message({
                    //     type: 'error',
                    //     message: '图片渲染失败，请稍后重试!'
                    // });
                    // setTimeout(()=>{
                    //     this.resetFlag();
                    //     this.form.mask = false;
                    // },1000)
                }
                
            },
            imgError(text){
                this.imgloadingText = text;
                setTimeout(()=>{
                    this.resetFlag();
                    this.form.mask = false;
                },1000);
            }
        }
    }
</script>
<style lang="scss" scoped>
    .customForm{
        padding: 0 40px;
        .formText{
            margin-bottom: 20px;
            .inlineText{
                white-space:nowrap;
                overflow:hidden;
                text-overflow:ellipsis;
            }
        }
        .formItem{
            margin-bottom: 30px;
        }
        .switchItem{
            width: 85%;
            display: inline-block;
        }
               
    }
</style>
<style lang="css" scoped>
.serviceedit >>> .el-dialog{
  background: url("../../static/dialogbg.png") no-repeat ;
  background-size: 100% 100%;
  box-shadow: none;
}
.serviceedit >>> .el-dialog__headerbtn{
  right: 12%;
  }
.serviceedit >>> .el-dialog__close{
  color: #fff;
  font-size: 25px;
}
.serviceedit >>> .el-dialog__header{
    text-align: center;
}
</style>
